<template>
  <el-tabs
    type="border-card"
    v-model="selectedTab"
    @tab-click="handleSwitchTabs"
  >
    <el-tab-pane
      v-for="item in tabInfo.list"
      v-model="item.name"
      :key="item.name"
      :label="item.title"
      :name="item.name"
      :disabled="tabInfo.loading"
    />
    <BasicForm
      v-loading="formLoading"
      ref="formData"
      :menuId="menuId"
      needSetSearchFields
      formItemWidth="100px"
      :formColumns="formItems"
      :dataSource="formData"
      :handleSearchForm="handleQueryForm"
      @getFormData="getFormData"
      @getSearchFormFields="getSearchFormFields"
    />
    <el-card class="sourcing-table-card" shadow="never">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <span>数据列表</span>
        <el-button
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-row>
      <BasicList
        showActionCol
        :loading="tableInfo.loading"
        :show-select-col="false"
        :data-source="tableInfo.list"
        :columns="tableInfo.columns"
        :actionColWidth="actionColWidth"
        :tableHeight="493"
        :actionRender="renderTableBtnAction"
        :pagination="pagination"
        :total="total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      />
    </el-card>
  </el-tabs>
</template>
<script>
import BasicPage from '@/mixins/sourcing/basicPage';
import SearchFields from '@/mixins/sourcing/searchFields';
import BasicForm from '@/pages/sourcing/components/BasicForm';
import BasicList from '@/pages/sourcing/components/BasicList';
import { getTableAction } from '@/utils/getBtnsRender';
import { createExcelByExport } from '@/utils/bizUtils';
import { handleOpenNewPageByName } from '@/pages/sourcing/utils';
import { FORM_ITEMS, TABLE_COLUMNS, ACTION_WIDTH_OBJ } from './constants';
import {
  querySelfPurchaseListService,
  exportSelfPurchaseListService,
  cancelInquiryService,
  generateOrderService,
  reinquiryService,
  getOAInfoService
} from '@api/sourcing/selfPurchaseInquiry';

export default {
  mixins: [BasicPage, SearchFields],
  components: {
    BasicForm,
    BasicList
  },
  data () {
    return {
      menuId: 203,
      formItems: FORM_ITEMS,
      selectedTab: '100',
      tableInfo: {
        loading: false,
        columns: TABLE_COLUMNS,
        list: []
      },
      tabInfo: {
        list: [
          { title: '全部状态', name: '' },
          { title: '询价中', name: '100' },
          { title: '待订货审批', name: '200' },
          { title: '待生成订单', name: '300' },
          { title: '已完成', name: '400' },
          { title: '询价取消', name: '500' },
        ],
        loading: false
      },
      loadingFn: state => { this.tableInfo.loading = state },
    }
  },
  computed: {
    actionColWidth () {
      return ACTION_WIDTH_OBJ[this.selectedTab] || 180
    }
  },
  methods: {
    init () {
      this.formData.billStatus = '100';
      const { sts } = this.$route.query;
      if (sts) {
        this.formData.billStatus = sts;
        this.selectedTab = sts;
      }
      this.getTableData()
    },
    // tab切换
    handleSwitchTabs (type) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
      this.formData.billStatus = type.name
      this.pagination.pageNum = 1
      this.getTableData()
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '查看', method: this.handleView },
      ]
      // 询价中
      if (row.billStatus == 100) {
        actionList.push({ label: '询价取消', method: this.handleCancelInquery })
      }
      // 待订货审批
      if (row.billStatus == 200) {
        actionList.push({ label: '审批流', method: this.handleAudit })
      }
      // 待生成订单
      if (row.billStatus == 300) {
        actionList.push(
          { label: '生成订单', method: this.handleGenerateOrder },
          { label: '重新询价', method: this.handleReinquiry }
        )
      }
      return getTableAction({ h, row, actionList })
    },
    // 格式化查询条件
    formatSearchParams () {
      const {
        creationDate = [],
        reqPurchaseOrderTime = []
      } = this.formData;
      const [
        creationDateStart = '',
        creationDateEnd = ''
      ] = creationDate || [];
      const [
        reqPurchaseOrderTimeStart = '',
        reqPurchaseOrderTimeEnd = ''
      ] = reqPurchaseOrderTime || [];
      return {
        creationDateStart,
        creationDateEnd,
        reqPurchaseOrderTimeStart,
        reqPurchaseOrderTimeEnd,
        ..._.omit(this.formData, 'creationDate', 'reqPurchaseOrderTime'),
      }
    },
    // 获取表格数据
    async getTableData () {
      const params = {
        ...this.formatSearchParams(),
        ...this.pagination
      }
      const res = await querySelfPurchaseListService(params, this.loadingFn)
      if (res?.data) {
        const { list, totalSize } = res.data
        this.tableInfo.list = list
        this.total = totalSize
      } else {
        this.tableInfo.list = []
        this.total = 0
      }
    },
    // 数据导出
    async handleExport () {
      const res = await exportSelfPurchaseListService(
        { ...this.formatSearchParams() },
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ res, excelTitle: '自进货询价列表' });
      }
    },
    // 查看
    handleView (row) {
      const {
        billStatus,
        selfPurchaseBillId
      } = row;
      const routerName = billStatus == 100 ? 'selfPurchaseQuotationInfo' : 'selfPurchaseCalibrationView';
      handleOpenNewPageByName(
        this,
        routerName,
        { selfPurchaseBillId }
      )
    },
    // 询价取消
    async handleCancelInquery (row) {
      const { selfPurchaseBillId } = row;
      const res = await cancelInquiryService(
        { selfPurchaseBillId },
        this.loadingFn
      )
      if (res) {
        this.$message.success('询价取消成功')
        this.getTableData()
      }
    },
    // 审批流
    async handleAudit (row) {
      if (!row.flowId) {
        return this.$message.warning('无审批ID')
      }
      const res = await getOAInfoService({ flowId: row.flowId }, this.loadingFn)
      if (res?.data) {
        window.open(res.data)
      }
    },
    // 生成订单
    async handleGenerateOrder (row) {
      // 校验是否为线索供应商
      const res = await generateOrderService(row.sourcingSupplierIdList, this.loadingFn)
      if (res) {
        if (row.sourcingSupplierIdList.length > 1) {
          handleOpenNewPageByName(this,
            'productContract',
            {
              sourcingBillId: row.selfPurchaseBillId,
              pushType: 'selfPurchase'
            }
          )
        } else {
          handleOpenNewPageByName(
            this,
            'selfPurchaseGenerateOrder',
            {
              supplierId: row.supplierId,
              sourcingSupplierId: row.sourcingSupplierIdList[0],
              pushType: 'selfPurchase'
            }
          )
        }
      }
    },
    // 重新询价
    handleReinquiry (row) {
      this.$confirm('您确定要重新询价吗，历史定标结果将会清空', '提示', {
        type: 'warning',
      }).then(() => {
        this.reinquiryAction(row)
      }).catch(() => {});
    },
    async reinquiryAction (row) {
      const { selfPurchaseBillId } = row;
      const res = await reinquiryService(
        { selfPurchaseBillId },
        this.loadingFn
      )
      if (res) {
        this.$router.push({
          name: 'selfPurchaseQuotationInfo',
          query: { selfPurchaseBillId } }
        )
      }
    },
  }
}
</script>
